//
//  AuthLocationViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/10/10.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "AuthLocationViewController.h"
#import "UIColor+Hex.h"
#import "MBProgressHUD+MJ.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import "AFHTTPRequestOperationManager.h"
#import "CityViewController.h"
#import "AuthViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapFoundationKit/AMapServices.h>
#import <AMapLocationKit/AMapLocationKit.h>


#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试
@interface AuthLocationViewController ()
@property UIScrollView *scrollView;
@property NSMutableArray *btnArrays;
@property NSMutableArray *data;
@property NSInteger height_item;
@property UILabel *loc_lab;
@end

@implementation AuthLocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    
    _data = [[NSMutableArray alloc]init];
    [self initView];
    [self initCompleteBlock];
    [self configLocationManager];
    
}
- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置不允许系统暂停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //设置允许在后台定位
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    
    //设置定位超时时间
    //[self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    //[self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    //进行单次定位请求
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}
- (void)initCompleteBlock
{
    __weak AuthLocationViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            //如果为定位失败的error，则不进行annotation的添加
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        //得到定位信息，添加annotation
        if (location)
        {
            NSLog(@"%@",[NSString stringWithFormat:@"%@-%@-%.2fm", regeocode.citycode, regeocode.city, location.horizontalAccuracy]);
            NSString *city = [regeocode.city substringToIndex:regeocode.city.length - 1];
            _loc_lab.text = [NSString stringWithFormat:@"    %@",city];
            [self getData:city];
        }
    };
}

-(void)initView{
    _scrollView= [[UIScrollView alloc]init];
    int height = 0;
    
    //当前位置
    _loc_lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    _loc_lab.text = @"    获取位置";
    _loc_lab.font = [UIFont systemFontOfSize:13];
    _loc_lab.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_loc_lab];
    height = height + 50;
    
    //当前区域
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, height, ScreenWidth, 50)];
    view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    [_scrollView addSubview:view];
    NSString *str1 = @"    当前区域";
    CGSize size = [str1 sizeWithFont:[UIFont systemFontOfSize:13]];
    UILabel *title_lab = [[UILabel alloc]initWithFrame:CGRectMake(0, height, size.width, 50)];
    title_lab.text = str1;
    title_lab.font = [UIFont systemFontOfSize:13];
    
    [_scrollView addSubview:title_lab];
    
    NSString *str2 = @"添加服务区域";
    size = [str2 sizeWithFont:[UIFont systemFontOfSize:15]];
    UIButton *add_btn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - size.width - 20, height + (50 - size.height) / 2, size.width, size.height)];
    [add_btn setTitle:str2 forState:UIControlStateNormal];
    [add_btn setTitle:str2 forState:UIControlStateSelected];
    [add_btn setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    add_btn.titleLabel.font = [UIFont systemFontOfSize:13];
    [add_btn.layer setBorderWidth:1];
    [add_btn.layer setBorderColor:[UIColor colorWithHexString:@"#ff7e00"].CGColor];
    [add_btn addTarget:self action:@selector(city_click) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:add_btn];
    
    height = height + 50;
    
    _height_item = height;
    
    
    
    _scrollView.frame = CGRectMake(0, 0, ScreenWidth, height);
    [self.controlView addSubview:_scrollView];
}


-(void)updateLoaction{
    _btnArrays = [[NSMutableArray alloc]init];
    UIView *view = [self.view viewWithTag:111];
    if (view != nil) {
        [view removeFromSuperview];
    }
    view = [[UIView alloc]init];
    view.tag = 111;
    int height = 15;
    int widght = ( ScreenWidth - 80 ) / 3;
    for (int i = 0; i < _data.count; i++) {
        
        NSDictionary *d = _data[i];
        UIButton *btn = [[UIButton alloc]init];
        btn.tag = i;
        if (i % 3 == 0) {
            btn.frame = CGRectMake(20, height, widght, 30);
        }
        if (i % 3 == 1) {
            btn.frame = CGRectMake(40 + widght, height, widght, 30);
        }
        if (i % 3 == 2) {
            btn.frame = CGRectMake(60 + widght * 2, height, widght, 30);
            height = height + 15;
            height = height + 30;
        }
        [btn setTitle:d[@"regionName"] forState:UIControlStateNormal];
        [btn setTitle:d[@"regionName"] forState:UIControlStateSelected];
        [btn setTitleColor:[UIColor colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [btn setBackgroundImage:[self createImageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [btn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#ff7e00"]] forState:UIControlStateSelected];
        btn.titleLabel.font = [UIFont systemFontOfSize:13];
        [btn.layer setBorderColor:[UIColor colorWithHexString:@"#4c4c4c"].CGColor];
        [btn.layer setBorderWidth:1];
        [btn addTarget:self action:@selector(location_text_click:) forControlEvents:UIControlEventTouchUpInside];
        [_btnArrays addObject:btn];
        
        [view addSubview:btn];
    }
    
    view.frame = CGRectMake(0, _height_item, ScreenWidth, height);
    _scrollView.frame = CGRectMake(0, 0, ScreenWidth,  _height_item + height);
    [_scrollView addSubview:view];
    _scrollView.contentSize=  CGSizeMake(ScreenWidth, _height_item + height);
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}
- (IBAction)back_click:(id)sender {
    if (_btnArrays.count > 0) {
        NSMutableString *ids = [[NSMutableString alloc]init];
        NSMutableString *names = [[NSMutableString alloc]init];
        for (UIButton *btn in _btnArrays) {
            if (btn.selected) {
                [names appendFormat:@"%@,",btn.titleLabel.text];
                [ids appendFormat:@"%@,",_data[btn.tag][@"id"]];
            }
        }
        AuthViewController *auth = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 2];
        auth.auth_location = @"";
        auth.auth_location2 = @"";
        if (![ids isEqualToString:@""]) {
            auth.auth_location2  = [ids substringToIndex:ids.length - 1];
        }
        if (![names isEqualToString:@""]) {
            auth.auth_location  = [names substringToIndex:names.length - 1];
        }

        
        [self.navigationController popToViewController:auth animated:YES];
        
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)getData:(NSString *) regionName{
    NSString *userId = [UserDefaultUtil getUserId];
    
    
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:userId forKey:@"identifier"];
    [dic setObject:regionName forKey:@"regionName"];
    [dic setObject:@"2" forKey:@"type"];
    
    
    HttpReauestParam *param = [[HttpReauestParam alloc] initWithData:@"county_level_city_get" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];

    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        if ([data[@"success"] boolValue]) {
            NSArray *d = data[@"result"];
            
            
            [_data addObjectsFromArray:d];
            [self updateLoaction];
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];

}
-(NSString*)dictionaryToJson:(id)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

-(void)city_click{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    CityViewController *vc = [sb instantiateViewControllerWithIdentifier:@"auth_city_view"];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)viewDidAppear:(BOOL)animated{
    if (self.cityStr != nil && ![self.cityStr isEqualToString:@""]) {
        [self getData:self.cityStr];
    }
    [super viewDidAppear:animated];
}

-(void)location_text_click:(UIButton *)button{
   // int tag = button.tag;
    if (button.selected) {
        [button.layer setBorderColor:[UIColor colorWithHexString:@"#4c4c4c"].CGColor];
        [button.layer setBorderWidth:1];
        button.selected = NO;
    }else{
        [button.layer setBorderColor:[UIColor colorWithHexString:@"#ff7e00"].CGColor];
        [button.layer setBorderWidth:1];
    
        button.selected = YES;
    }
}
@end
